﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;

using Jumpton.Persistent;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.Entity;
/// <summary>
/// 自定义填写控件
/// </summary>
public partial class CustomTable : System.Web.UI.UserControl
{
    private ObjectTable _ot = null;
    protected void Page_Load(object sender, EventArgs e)
    {
         
    }

    protected override void  OnInit(EventArgs e)
    {
        bool includeJS = false;
      
        if (string.IsNullOrEmpty(TableName))
            return;
        //获取该张表的所有数据
        _ot = new Jumpton.SFA.Server.BusinessRule.System.TableConfigManager().LoadByTable(TableName);

        if (_ot == null || _ot.Count == 0)
            return;

        Table table = new Table();

        table.Attributes.Add("style", "width:80%;text-align:center;");
        if (!string.IsNullOrEmpty(TableCssClass))
        {
            table.CssClass = TableCssClass;
        }
        TableRow tr = null;
        int countCol = 0;
        foreach (ObjectRow row in _ot)
        {
            TableConfig config = row as TableConfig;
            if (!config.Enabled)
                continue;
            if (countCol == 0)
            {
                tr = new TableRow();
                table.Rows.Add(tr);
            }
            if (countCol < RepeatColumns)
            {
                //添加标题
                TableCell cell = new TableCell();
                cell.Text = config.Title;
                cell.Attributes.Add("nowrap", "nowrap");
                tr.Cells.Add(cell);
                if (!string.IsNullOrEmpty(TitleCssClass))
                {
                    cell.CssClass = TitleCssClass;
                }
                //添加输入项
                cell = new TableCell();
                WebControl control  = new TextBox();
                (control as TextBox).MaxLength = 32;

                control.ID = config.ColumnName.ToUpper();
                
                if (!string.IsNullOrEmpty(ControlCssClass))
                {

                    control.CssClass = ControlCssClass;
                }
                switch (config.Type)
                {
                    case 1:  //整数
                        {
                            CompareValidator compare = new CompareValidator();
                            compare.ControlToValidate =control.ClientID;
                            compare.ErrorMessage = config.Title + "输入值只能是整数";
                            compare.Operator = ValidationCompareOperator.DataTypeCheck;
                            compare.Type = ValidationDataType.Integer;
                            cell.Controls.Add(compare);
                            break;
                        }
                    case 2: //小数
                        {
                            CompareValidator compare = new CompareValidator();
                            compare.ControlToValidate = control.ClientID;
                            compare.ErrorMessage = config.Title + "输入值只能是小数";
                            compare.Operator = ValidationCompareOperator.DataTypeCheck;
                            compare.Type = ValidationDataType.Double;
                            cell.Controls.Add(compare);
                            break;
                        }
                    case 3: //日期
                        {
                            (control as TextBox).ReadOnly = true;
                            control.Attributes.Add("onfocus", "WdatePicker()");
                            if (!includeJS)
                            {
                                var c = new System.Web.UI.HtmlControls.HtmlGenericControl();
                                c.TagName = "script";
                                c.Attributes.Add("type", "text/javascript");
                                c.Attributes.Add("src", Request.ApplicationPath + "/JavaScript/My97DatePicker/WdatePicker.js");
                               
                                cell.Controls.Add(c);
                                includeJS = true;
                            }
                            break;
                        }
                    case 4: //是否型
                        {
                            control = new CheckBox();
                            //cell.Controls.Add(control);
                            break;
                        }
                    case 5: //选择型
                        {
                            DropDownList list = new DropDownList();
                            list.ID = config.ColumnName.ToUpper();
                            control =list;
                            foreach (string str in config.ListItem.Split(','))
                            {
                                list.Items.Add(new ListItem(str,str));
                            }
                            break;
                        }
                    default:
                        {
                            break;
                        }

                }
                cell.Controls.AddAt(0,control);
                tr.Cells.Add(cell);
                countCol++;
            }

            if (countCol == RepeatColumns)
            {
                countCol = 0;

            }
        }
        Controls.Add(table);

        base.OnInit(e);
    }

   

    public object DataSource
    {
        get;
        set;
    }

    public string TableCssClass
    {
        get;
        set;
    }

    public string TitleCssClass
    {
        get;
        set;
    }

    public string ControlCssClass
    {
        get;
        set;
    }

    /// <summary>
    /// 绑定数据
    /// </summary>
    public override void DataBind()
    {
        base.DataBind();
        if (_ot == null)
            return;
        if (DataSource == null)
            return;


        /*
         * 判断对象的类型，如果对象是数据行则采用不同的数据类型
         */

        if (DataSource is ObjectRow)
        {
            ObjectRow source = DataSource as ObjectRow;
            foreach (ObjectRow row in _ot)
            {
                TableConfig config = row as TableConfig;
                if (config == null || !config.Enabled)
                    continue;
                try
                {
                    var value = source.GetPropertyValue(config.ColumnName);
                    if (value != null)
                    {
                        this[config.ColumnName] = value.ToString();
                    }
                }
                catch { }
            }


        }
        else if (DataSource is System.Data.DataRow)
        {
            System.Data.DataRow source = DataSource as System.Data.DataRow;
            foreach (ObjectRow row in _ot)
            {
                TableConfig config = row as TableConfig;
                if (config == null || !config.Enabled)
                    continue;
                try
                {
                    var value = source[config.ColumnName];
                    if (value != null)
                    {
                        this[config.ColumnName] = value.ToString();
                    }
                }
                catch { }
            }
        }
        else if (DataSource is System.Data.DataRowView)
        {
            System.Data.DataRowView source = DataSource as System.Data.DataRowView;
            foreach (ObjectRow row in _ot)
            {
                TableConfig config = row as TableConfig;
                if (config == null || !config.Enabled)
                    continue;
                try
                {
                    var value = source[config.ColumnName];
                    if (value != null)
                    {
                        this[config.ColumnName] = value.ToString();
                    }
                }
                catch { }
            }
        }
     
    }

    public void SaveValue(object source)
    {
        if (string.IsNullOrEmpty(TableName))
            return;
        //获取该张表的所有数据
        _ot = new Jumpton.SFA.Server.BusinessRule.System.TableConfigManager().LoadByTable(TableName);
      
        if (_ot == null || _ot.Count == 0)
            return;
        if (source == null)
            return;
      


        /*
         * 判断对象的类型，如果对象是数据行则采用不同的数据类型
         */

        if (source is ObjectRow)
        {
            ObjectRow or = source as ObjectRow;
            foreach (ObjectRow row in _ot)
            {
                TableConfig config = row as TableConfig;
                if (config == null || !config.Enabled)
                    continue;
                try
                {
                    or.SetPropertyValue(config.ColumnName,this[config.ColumnName]);
                  
                }
                catch { }
            }


        }
        else if (source is System.Data.DataRow)
        {
            var dr = source as System.Data.DataRow;
            foreach (ObjectRow row in _ot)
            {
                TableConfig config = row as TableConfig;
                if (config == null || !config.Enabled)
                    continue;
                try
                {
                    dr[config.ColumnName] = this[config.ColumnName];
                
                }
                catch { }
            }
        }
        else if (source is System.Data.DataRowView)
        {
            var dr = (source as System.Data.DataRowView).Row;
            foreach (ObjectRow row in _ot)
            {
                TableConfig config = row as TableConfig;
                if (config == null || !config.Enabled)
                    continue;
                try
                {
                    dr[config.ColumnName] = this[config.ColumnName];

                }
                catch { }
            }
        }
    }

    /// <summary>
    /// 获取指定字段的值
    /// </summary>
    /// <param name="columnName"></param>
    /// <returns></returns>
    public string this[string columnName]
    {
        get
        {
            if (string.IsNullOrEmpty(columnName))
                return null;
            Control table = null;
            foreach (Control ctl in Controls)
            {
                if (ctl is Table)
                {
                    table = ctl;
                    break;
                }
            }
            if (table == null)
                return "";
            Control control = table.FindControl(columnName.ToUpper());
            if (control == null)
                return null;
            if (control is CheckBox)
                return (control as CheckBox).Checked ? "1" : "0";
            else if (control is DropDownList)
                return (control as DropDownList).SelectedValue;
            else
            {
                (control as TextBox).Text = Request[control.UniqueID];
                return Request[control.UniqueID];
            }
        }
        set
        {
            if (string.IsNullOrEmpty(columnName))
                return;
            Control table = null;
            foreach (Control ctl in Controls)
            {
                if (ctl is Table)
                {
                    table = ctl;
                    break;
                }
            }
            if (table == null)
                return;
            Control control = table.FindControl(columnName.ToUpper());
            if (control == null)
                return;
            if (control is CheckBox)
                (control as CheckBox).Checked = "1".Equals(value); 
            else if(control is DropDownList)
                try
                {
                    (control as DropDownList).Text = value;
                }
                catch { }
            else
             (control as TextBox).Text = value;
        }
    }

    /// <summary>
    /// 对象表名
    /// </summary>
    public string TableName
    {
        get;
        set;
    }

    public string CssTableID
    {
        get;
        set;
    }

    /// <summary>
    /// 排列的方向
    /// </summary>
    public RepeatDirection RepeatDirection
    {
        get;
        set;
    }

    /// <summary>
    /// 排列的列数
    /// </summary>
   
    public int RepeatColumns
    {
        get;
        set;
    }
}
